/*
Copyright (c) 2009 Peter "Corsix" Cawley

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/

#include "config.h"
#include "../Src/main.h"
#include "../Src/bootstrap.h"
#include <stack>
#include <SDL.h>
#include "android_debug.h"
#include <unistd.h>
#include <dlfcn.h>

// Template magic for checking type equality
template <typename T1, typename T2>
struct types_equal{ enum{
    result = -1,
}; };

template <typename T1>
struct types_equal<T1, T1>{ enum{
    result = 1,
}; };


// used for JIT control
typedef int (*luaJIT_setmode_fn)(lua_State *, int, int);
enum
{
  LUAJIT_MODE_ENGINE,       /* Set mode for whole JIT engine. */
  LUAJIT_MODE_DEBUG,        /* Set debug mode (idx = level). */

  LUAJIT_MODE_FUNC,     /* Change mode for a function. */
  LUAJIT_MODE_ALLFUNC,      /* Recurse into subroutine protos. */
  LUAJIT_MODE_ALLSUBFUNC,   /* Change only the subroutines. */

  LUAJIT_MODE_TRACE,        /* Flush a compiled trace. */

  LUAJIT_MODE_WRAPCFUNC = 0x10, /* Set wrapper mode for C function calls. */

  LUAJIT_MODE_MAX
};
#define LUAJIT_MODE_OFF     0x0000  /* Turn feature off. */
#define LUAJIT_MODE_ON      0x0100  /* Turn feature on. */
#define LUAJIT_MODE_FLUSH   0x0200  /* Flush JIT-compiled code. */

//! Program entry point
/*!
    Prepares a Lua state for, and catches errors from, CorsixTH_lua_main(). By
    executing in Lua mode as soon as possible, errors can be nicely caught
    sooner, hence this function does as little as possible and leaves the rest
    for CorsixTH_lua_main().
*/
int main(int argc, char** argv)
{
    struct compile_time_lua_check
    {
        // Lua 5.1, not 5.0, is required
        int lua_5_point_1_required[LUA_VERSION_NUM >= 501 ? 1 : -1];

        // Lua numbers must be doubles so that the mantissa has at least
        // 32 bits (floats only have 24 bits)
        int number_is_double[types_equal<lua_Number, double>::result];
    };

    // try to enable the JIT
    luaJIT_setmode_fn lj_set_mode = 0;
    void * h = dlopen ("liblua.so", RTLD_LAZY);
    if(h)
        lj_set_mode = (luaJIT_setmode_fn)dlsym(h, "luaJIT_setmode");

    LOGW("JIT enabled: %d", lj_set_mode != 0);

    bool bRun = true;
    while(bRun)
    {
        lua_State *L = NULL;

        L = luaL_newstate();
        if(L == NULL)
        {
            LOGE("Fatal error starting CorsixTH: "
                "Cannot open Lua state.");
            return 0;
        }
        else if(lj_set_mode)
        {
            // enable JIT
            int st = lj_set_mode(L, 0, LUAJIT_MODE_ENGINE|LUAJIT_MODE_ON);
            LOGW("JIT started: %d", st);
        }

        lua_atpanic(L, CorsixTH_lua_panic);
        luaL_openlibs(L);
        lua_settop(L, 0);
        lua_pushcfunction(L, CorsixTH_lua_stacktrace);
        lua_pushcfunction(L, CorsixTH_lua_main);

        // Move command line parameters onto the Lua stack
        lua_checkstack(L, argc);
        for(int i = 0; i < argc; ++i)
        {
            lua_pushstring(L, argv[i]);
        }

        if(lua_pcall(L, argc, 0, 1) != 0)
        {
            const char* err = lua_tostring(L, -1);
            if(err != NULL)
            {
                LOGW("%s (from 2)", err);
            }
            else
            {
                LOGW("An error has occured in CorsixTH: "
                    "Uncaught non-string Lua error");
            }
            lua_pushcfunction(L, Bootstrap_lua_error_report);
            lua_insert(L, -2);
            if(lua_pcall(L, 1, 0, 0) != 0)
            {
                LOGW("%s (from 3)", lua_tostring(L, -1));
            }
        }

        lua_getfield(L, LUA_REGISTRYINDEX, "_RESTART");
        bRun = lua_toboolean(L, -1) != 0;

        // Get cleanup functions out of the Lua state (but don't run them yet)
        std::stack<void(*)(void)> stkCleanup;
        lua_getfield(L, LUA_REGISTRYINDEX, "_CLEANUP");
        if(lua_type(L, -1) == LUA_TTABLE)
        {
            for(unsigned int i = 1; i <= lua_objlen(L, -1); ++i)
            {
                lua_rawgeti(L, -1, (int)i);
                stkCleanup.push((void(*)(void))lua_touserdata(L, -1));
                lua_pop(L, 1);
            }
        }

        lua_close(L);

        // The cleanup functions are executed _after_ the Lua state is fully
        // closed, and in reserve order to that in which they were registered.
        while(!stkCleanup.empty())
        {
            if(stkCleanup.top() != NULL)
                stkCleanup.top()();
            stkCleanup.pop();
        }

        if(bRun)
        {
            LOGW("Restarting...");
        }
    }

    LOGW("Leaving...");
    return 0;
}
